package example.demo.atomic;

import example.demo.cas.CASUse;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class AtomicInterImpl {

    // setup to use Unsafe.compareAndSwapInt for updates
    private static final Unsafe unsafe /*= Unsafe.getUnsafe()*/;
    private static final long valueOffset;

    static {
        try {
            Class<Unsafe> unsafeClass = Unsafe.class;
            Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
            valueOffset = unsafe.objectFieldOffset
                    (AtomicInterImpl.class.getDeclaredField("value"));
        } catch (Exception ex) {
            throw new Error(ex);
        }
    }

    private volatile int value;

    public int valueAdd() {
        //todo 记录加载主存的value
        int val = value;
        //todo 使用value，value+1 这两value的值可能相同，也可能不同
        while (!unsafe.compareAndSwapInt(this, valueOffset, val, val + 1)) {
            //todo 失败，则重新加载主存的value
            val = value;
        }
        //todo 返回当前线程计算的结果
        return val + 1;
//      todo  return value;//返回的主存的结果，也就可能返回不是自己计算的结果
    }

    public int getValue() {
        return value;
    }

    public static void main(String[] args) {

    }
}
